<?php

/**
 * JingYao-backend
 *
 * @link     https://gitee.com/wang-zhihui-release/jingyao-backend
 * @apiDocument https://gitee.com/wang-zhihui-release/jingyao-backend/wikis/
 */

namespace App\Services;

use App\Enums\AdminCheckEnum;
use App\Enums\CheckStatusEnum;
use App\Events\CheckSuccess;
use App\Exceptions\ApiException;
use App\Format\CheckSuccessFormat;
use App\Format\RecruitmentFormat;
use App\Models\Recruitment;
use App\Models\UserProfile;
use Illuminate\Support\Facades\Log;

class RecruitmentService
{
    public function setRecruitmentForCheck(RecruitmentFormat $recruitmentFormat, int $userId)
    {
        $recruitmentFormat->setCheckStatus(CheckStatusEnum::CHECK_ING);
        $recruitmentFormat->setPushTime(time());
        $pushUserId = $recruitmentFormat->getUserId();
        /** @var null|UserProfile $userProfile */
        $userProfile = UserProfile::query()->where('user_id', $pushUserId)->select('check_status')->first();
        if (empty($userProfile)) {
            throw new ApiException('用户不存在', 1);
        }
        if ($userProfile->check_status != CheckStatusEnum::CHECK_ADOPT) {
            throw new ApiException('个人信息审核通过的用户才能发布招聘', 1);
        }
        if (! $recruitmentFormat->getId()) {
            Recruitment::query()->create($recruitmentFormat->toArrayNotNull());
            return true;
        }
        $id = $recruitmentFormat->getId();
        /** @var null|Recruitment $recruitment */
        $recruitment = Recruitment::query()->find($id);
        if (empty($recruitment)) {
            throw new ApiException('数据不存在', 1);
        }
        if ($recruitment->user_id != $userId) {
            Log::error('修改非自己的招聘', [
                'user_id' => $userId,
                'data_user_id' => $recruitmentFormat->getUserId(),
            ]);
            throw new ApiException('非法操作', 1);
        }
        $recruitment->update($recruitmentFormat->toArrayNotNull());
        return true;
    }

    public function checkRecruitment(int $id, int $checkStatus, ?string $checkMessage)
    {
        /** @var null|Recruitment $rectuiment */
        $rectuiment = Recruitment::query()->find($id);
        if (empty($rectuiment)) {
            throw new ApiException('数据不存在', 1);
        }
        $rectuiment->check_status = $checkStatus;
        if ($checkMessage) {
            $rectuiment->check_message = $checkMessage;
        }
        // 默认一个月过期
        if ($checkStatus == CheckStatusEnum::CHECK_ADOPT) {
            $rectuiment->expire_time = time() + (3600 * 24 * 30);
        }
        $rectuiment->save();
        event(new CheckSuccess(new CheckSuccessFormat([
            'check_status' => $checkStatus,
            'check_type' => AdminCheckEnum::CHECK_RECRUITMENT,
            'user_id' => $rectuiment->user_id,
        ])));
        return true;
    }

    public function setExpireTime(int $id, int $expireTime)
    {
        /** @var null|Recruitment $rectuiment */
        $rectuiment = Recruitment::query()->find($id);
        if (empty($rectuiment)) {
            throw new ApiException('数据不存在', 1);
        }
        if ($rectuiment->check_status != CheckStatusEnum::CHECK_ADOPT) {
            throw new ApiException('不能为未审核通过的招聘设置过期时间', 1);
        }
        $rectuiment->expire_time = $expireTime;
        $rectuiment->save();
        return true;
    }

    public function getRecruitmentList(int $page, int $pageSize, array $search)
    {
        $builder = Recruitment::query()
            ->where('expire_time', '>', time())
            ->where('check_status', CheckStatusEnum::CHECK_ADOPT);
        if (isset($search['job_name'])) {
            $builder->where('job_name', 'like', '%' . $search['job_name'] . '%');
        }
        if (isset($search['start_date'], $search['end_date'])) {
            $builder->where('push_time', '>=', strtotime($search['start_date']));
            if (strlen($search['end_date']) > 10) {
                $builder->where('push_time', '<=', strtotime($search['end_date']));
            } else {
                $builder->where('push_time', '<=', strtotime($search['end_date']) + (24 * 3600));
            }
        }
        if (isset($search['start_date']) && ! isset($search['end_date'])) {
            $builder->where('push_time', '>=', strtotime($search['start_date']));
        }
        if (! isset($search['start_date']) && isset($search['end_date'])) {
            if (strlen($search['end_date']) > 10) {
                $builder->where('push_time', '<=', strtotime($search['end_date']));
            } else {
                $builder->where('push_time', '<=', strtotime($search['end_date']) + (24 * 3600));
            }
        }
        $count = $builder->count();
        $list = $builder->orderByDesc('push_time')->skip(($page - 1) * $pageSize)->take($pageSize)->get();
        return [
            'page' => $page,
            'page_size' => $pageSize,
            'count' => $count,
            'list' => $list,
        ];
    }

    public function getRecruitmentListForAdmin(int $page, int $pageSize, array $search)
    {
        $builder = Recruitment::query();
        if (isset($search['job_name'])) {
            $builder->where('job_name', 'like', '%' . $search['job_name'] . '%');
        }
        if (isset($search['check_status'])) {
            $builder->where('check_status', $search['check_status']);
        }

        if (isset($search['start_date'], $search['end_date'])) {
            $builder->where('push_time', '>=', strtotime($search['start_date']));
            $builder->where('push_time', '<=', strtotime($search['end_date']) + (24 * 3600));
        }
        if (isset($search['start_date']) && ! isset($search['end_date'])) {
            $builder->where('push_time', '>=', strtotime($search['start_date']));
        }
        if (! isset($search['start_date']) && isset($search['end_date'])) {
            $builder->where('push_time', '<=', strtotime($search['end_date']) + (24 * 3600));
        }

        $count = $builder->count();
        $list = $builder
            ->orderByDesc('id')
            ->skip(($page - 1) * $pageSize)->take($pageSize)->get();

        return [
            'page' => $page,
            'page_size' => $pageSize,
            'count' => $count,
            'list' => $list,
        ];
    }

    public function delete(int $id)
    {
        /** @var null|Recruitment $rectuiment */
        $rectuiment = Recruitment::query()->find($id);
        if (empty($rectuiment)) {
            throw new ApiException('数据不存在', 1);
        }
        $rectuiment->delete();
        return true;
    }

    public function detail(int $id)
    {
        /** @var null|Recruitment $rectuiment */
        $rectuiment = Recruitment::query()
            ->where('check_status', CheckStatusEnum::CHECK_ADOPT)
            ->where('expire_time', '>', time())
            ->find($id);
        if (empty($rectuiment)) {
            throw new ApiException('数据不存在', 1);
        }
        return $rectuiment;
    }

    public function detailAdmin(int $id)
    {
        /** @var null|Recruitment $rectuiment */
        $rectuiment = Recruitment::query()->find($id);
        if (empty($rectuiment)) {
            throw new ApiException('数据不存在', 1);
        }
        return $rectuiment;
    }

    public function getMyRecruitment(int $page, int $pageSize, int $userId)
    {
        $builder = Recruitment::query()->where('user_id', $userId);

        $count = $builder->count();

        $list = $builder->skip(($page - 1) * $pageSize)->take($pageSize)->get();

        return [
            'page' => $page,
            'page_size' => $pageSize,
            'count' => $count,
            'list' => $list,
        ];
    }

    public function getMyRecruitmentDetail(int $id, int $userId)
    {
        $recruitment = Recruitment::query()->where('user_id', $userId)->find($id);
        if (empty($recruitment)) {
            throw new ApiException('数据不存在', 1);
        }
        return $recruitment;
    }
}
